<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    table {
      width: 500px;
      text-align: center;
      border-collapse: collapse;
    }
    th,
    td {
      border: 1px solid purple;
    }
  </style>
  <body>
    <table>
      <thead>
        <tr>
          <th>订单编号</th>
          <th>名称</th>
          <th>价格</th>
          <th>数量</th>
        </tr>
      </thead>
      <tbody></tbody>
    </table>
    <div class="total">
      <div>合计：<span class="amount">1000.00</span></div>
    </div>
  </body>
  <script>
    function ShoppingCart() {
      this.items = []
      this.totalPrice = 0
    }
    // 添加
    ShoppingCart.prototype.additem = function ({ id, name, price, quantity }) {
      this.items.push({ id, name, price, quantity })
    }
    // 删除
    ShoppingCart.prototype.removeitem = function (id) {
      const index = this.items.findIndex((item) => {
        return item.id === id
      })
      return this.items.splice(index, 1)
    }

    //  更新
    ShoppingCart.prototype.updateitem = function (id, quantity) {
      let item = this.items.find(function (item) {
        return item.id === id
      })

      let oldQuantity = item.quantity
      item.quantity = quantity
    }
    const cart = new ShoppingCart()
    const item = { id: 1, name: '牛奶', price: 20, quantity: 4 }
    const item1 = { id: 2, name: '面包', price: 10, quantity: 3 }
    const item2 = { id: 3, name: '鸡蛋', price: 5, quantity: 5 }

    cart.additem(item)
    cart.additem(item1)
    cart.additem(item2)
    // cart.removeitem(3)

    cart.updateitem(2, 10)
    console.log(cart)

    function renderCart(item) {
      const data = cart.items.map((item) => {
        return `
              <tr>
              <td>${item.id}</td>
               <td>${item.name}</td>
               <td>${item.price}</td>
               <td>${item.quantity}</td>
              </tr>
              `
      })
      const total = this.items.reduce(
        (prev, item) => prev + item.price * item.quantity,
        0
      )
      document.querySelector('tbody').innerHTML = data.join('')
      document.querySelector('.amount').innerHTML = total
    }
    renderCart.call(cart)
  </script>
</html>
